package com.wsc.personalblog.filter;

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(urlPatterns = "/*")
@Component
@Order(0)
public class CORSFilter implements Filter {
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Content-Length, X-Requested-With");

        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            chain.doFilter(req, res);
        }
        /**
         * 在上面的代码中，我们
         * 通过设置Access-Control-Allow-Origin响应头允许所有来源的请求，
         * 通过Access-Control-Allow-Methods响应头允许POST、GET、OPTIONS和DELETE请求，
         * 通过Access-Control-Max-Age响应头设置预检请求的缓存时间，
         * 通过Access-Control-Allow-Headers响应头允许Content-Type、Authorization、
         * Content-Length和X-Requested-With请求头。
         * 需要注意的是，在配置CORS过滤器时，要确保它在Spring Security过滤器链的前面，
         * 以确保CORS过滤器的优先级更高。可以通过将@Order注解应用于过滤器类来实现。
         */
    }
}
